using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Build;
using UnityEngine;

namespace CGF
{
    [CustomEditor(typeof(CGFConfig))]
    public class CGFConfigEditor : Editor
    {
        [MenuItem("CGFramework/框架配置 #A", priority = -800)]
        public static void OpenConfig()
        {
            var instance = Resources.Load(typeof(CGFConfig).Name);
            if (instance == null)
            {
                instance = CreateInstance<CGFConfig>();
                string assetPath = $"Assets/Scripts_Main/CGFramework/Resources/{typeof(CGFConfig).Name}.asset";
                AssetDatabase.CreateAsset(instance, assetPath);
                AssetDatabase.SaveAssets();
            }
            Selection.activeObject = instance;
        }

        private CGFConfig config;
        private SerializedObject serialized;
        private SerializedProperty packs;
        private SerializedProperty currPackIndex;

        void OnEnable()
        {
            config = (CGFConfig)target;
            serialized = new SerializedObject(target);
            packs = serializedObject.FindProperty("packs");
            currPackIndex = serializedObject.FindProperty("currPackIndex");
        }

        public override void OnInspectorGUI()
        {
            serialized.Update();
            EditorGUI.BeginChangeCheck();

            EditorGUILayout.Space();

            EditorGUILayout.PropertyField(packs);
            
            string[] options = GenerateOptions(packs);
            currPackIndex.intValue = Mathf.Clamp(currPackIndex.intValue, 0, options.Length - 1);
            int packIndex = EditorGUILayout.Popup("当前使用Pack", currPackIndex.intValue, options);
            
            EditorGUILayout.Space();

            config._editorUseAB = EditorGUILayout.Toggle("编辑器使用AB", config._editorUseAB);

            EditorGUILayout.Space();

            EditorGUILayout.LabelField("按需热更的目录(不会自动热更)");
            for (int i = 0; i < config.extraUpdateFolders.Count; i++)
            {
                if (i > config.extraUpdateFolders.Count - 1)
                {
                    config.extraUpdateFolders.RemoveAt(config.extraUpdateFolders.Count - 1);
                    return;
                }
                EditorGUILayout.BeginHorizontal();
                config.extraUpdateFolders[i].folderObj = EditorGUILayout.ObjectField(config.extraUpdateFolders[i].folderObj, typeof(DefaultAsset), true);
                if (GUILayout.Button("↑", GUILayout.MaxWidth(20)))
                {
                    if (i > 0)
                    {
                        List<Folder> newList = new List<Folder>();
                        for (int j = 0; j < config.extraUpdateFolders.Count; j++)
                        {
                            if (j == i - 1)
                            {
                                newList.Add(config.extraUpdateFolders[j + 1]);
                            }
                            else if (j == i)
                            {
                                newList.Add(config.extraUpdateFolders[j - 1]);
                            }
                            else
                            {
                                newList.Add(config.extraUpdateFolders[j]);
                            }
                        }
                        config.extraUpdateFolders = newList;
                        return;
                    }
                }
                if (GUILayout.Button("X", GUILayout.MaxWidth(25)))
                {
                    config.extraUpdateFolders.RemoveAt(i);
                }
                EditorGUILayout.EndHorizontal();
            }

            EditorGUILayout.Space();

            if (GUILayout.Button("+"))
            {
                config.extraUpdateFolders.Add(null);
            }

            EditorGUILayout.Space();

            if (GUILayout.Button("应用"))
            {
                Apply(packIndex);
            }

            if (EditorGUI.EndChangeCheck())
            {
                Apply(packIndex);
            }
        }

        private string[] GenerateOptions(SerializedProperty arrayProperty)
        {
            int arraySize = arrayProperty.arraySize;
            string[] options = new string[arraySize];
            for (int i = 0; i < arraySize; i++)
            {
                SerializedProperty element = arrayProperty.GetArrayElementAtIndex(i);
                SerializedProperty nameProperty = element.FindPropertyRelative("tag");
                options[i] = $"{i}: {nameProperty.stringValue}";
            }
            if (arraySize == 0)
            {
                return new string[] { "暂无包配置" };
            }
            return options;
        }

        private void Apply(int packIndex)
        {
            //要先执行修改，否则后续读到的是旧值，最后再执行一次，否则虽然编辑器上变了，但执行打包会还原回来
            serialized.ApplyModifiedProperties();
            serializedObject.ApplyModifiedProperties();

            for (int i = 0; i < config.extraUpdateFolders.Count; i++)
            {
                config.extraUpdateFolders[i].path = AssetDatabase.GetAssetPath(config.extraUpdateFolders[i].folderObj).Replace("\\", "/");
            }
            
            currPackIndex.intValue = packIndex;
            var pack = config.packs[packIndex];
            PlayerSettings.companyName = pack.companyName;
            PlayerSettings.productName = pack.productName;
            PlayerSettings.SetIcons(NamedBuildTarget.Unknown, new []{pack.appIcon}, IconKind.Any);//用NamedBuildTarget.Unknown就会设置Default Icon
            PlayerSettings.SetApplicationIdentifier(NamedBuildTarget.iOS, pack.packName);
            PlayerSettings.SetApplicationIdentifier(NamedBuildTarget.Android, pack.packName);
            if (!string.IsNullOrEmpty(pack.firebaseIOSUrlScheme))
            {
                PlayerSettings.iOS.iOSUrlSchemes = new[] { pack.firebaseIOSUrlScheme };
            }
            PlayerSettings.iOS.cameraUsageDescription = "App need Camera";
            PlayerSettings.iOS.microphoneUsageDescription = "App need Microphone";
            PlayerSettings.iOS.locationUsageDescription = "App need Location";
            PlayerSettings.insecureHttpOption = InsecureHttpOption.AlwaysAllowed;
            PlayerSettings.bundleVersion = $"{pack.versionName}.{pack.versionCode}";
            PlayerSettings.Android.bundleVersionCode = pack.versionCode;
            PlayerSettings.Android.keystoreName = pack.keystorePath;
            PlayerSettings.Android.keyaliasName = pack.keystoreAlias;
            PlayerSettings.Android.keystorePass = pack.keystorePasswd;
            PlayerSettings.Android.keyaliasPass = pack.keystorePasswd;
            PlayerSettings.iOS.buildNumber = pack.versionCode.ToString();
            
            EditorUtility.SetDirty(config);
            AssetDatabase.SaveAssets();
            
            //最后再执行一次
            serialized.ApplyModifiedProperties();
            serializedObject.ApplyModifiedProperties();
        }
    }
}
